﻿using Microsoft.EntityFrameworkCore;
using MyWeb.ServiceBus.Common;
using MyWeb.ServiceBus.Model.Dto;
using MyWeb.ServiceBus.Model.Models;
using MyWeb.ServiceBus.Services.Db;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.ServiceBus.Services.Impl
{
    public class SubServerService : BaseEFService<SubServer>, ISubServerService
    {
        private readonly Context db;
        public SubServerService(Context context) : base(context)
        {
            db = context;
        }

        public async Task<List<SubServerDto>> QueryPageAsync(SubServerDto dto)
        {
            var where = ExtLinq.True<SubServerDto>();
            if (!string.IsNullOrEmpty(dto.Key))
            {
                where = where.And(a => a.ServerCode.Contains(dto.Key));
            }
            if(dto.AppId > 0)
            {
                where = where.And(a => a.AppId == dto.AppId);
            }
            var linq = from s in db.SubServer
                       join ss in db.SysService on s.ServerId equals ss.Id
                       where ss.Code.Contains(dto.Key)
                       select new SubServerDto
                       {
                           Id = s.Id,
                           AppId = s.AppId,
                           ServerId = s.ServerId,
                           GatewayId = s.GatewayId,
                           ServerCode = ss.Code,
                           Version =  s.Version,
                           SubTime = s.SubTime
                       };
            var result = new List<SubServerDto>();
            if(dto.Pagination != null)
            {
                dto.Pagination.DataCount = await linq.CountAsync();
                result = await linq
                    .Skip((dto.Pagination.Page - 1) * dto.Pagination.PageSize)
                    .Take(dto.Pagination.PageSize)
                    .ToListAsync();
            }
            else
            {
                result = await linq.ToListAsync();
            }
            return result;
        }

    }
}
